package view.audit
{
	import business.ApplyClassDelegate;
	import business.GameDelegate;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.system.System;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.CheckBox;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.Label;
	import mx.controls.LinkButton;
	import mx.controls.RadioButton;
	import mx.controls.SWFLoader;
	import mx.controls.TextArea;
	import mx.controls.TextInput;
	import mx.core.Application;
	import mx.events.CloseEvent;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.utils.StringUtil;
	
	import util.GCUtil;
	import util.LogUtil;

	[Bindable]
	public class ApplyClassAuditClass extends VBox
	{
		//page 
		public var pageIndices:Array;
		public var page:int;
		public var pagecnt:int;
	    public var pageVolume:int;

		//界面元件
		public var item_id:TextInput;
		public var item_bid:TextInput;
		public var item_aid:TextInput;
		public var item_avatar:TextInput;
		public var item_sid:TextInput;
		public var item_mode_label:Label;
		public var item_mode:ComboBox;
		public var item_title:TextInput;
		public var item_catalog:TextInput;
		public var item_saveTime:TextInput;
		public var item_fileSize:TextInput;
		public var item_totalTime:TextInput;
		public var item_click:TextInput;
		public var item_flower:TextInput;
		public var item_favorite:TextInput;
		public var item_comment:TextInput;
		public var item_gameid:TextInput;
		public var item_game:TextInput;
		public var item_guildid:TextInput;
		public var item_tag:TextInput;
		public var item_adwords:Object;
		public var item_editorWords:Object;
		public var item_sendMsg:Object;
		public var item_label_reaudit:Label;
		public var item_audit:RadioButton;
		public var item_share:CheckBox;
		public var item_class:CheckBox;
		public var item_delete:RadioButton;
		public var item_unaudit:RadioButton;
		public var item_eventId:TextInput;
		public var item_player:SWFLoader;
		public var item_playerBox:VBox;
		public var item_player_hbox:HBox;
		public var item_reason:TextArea;
		public var item_rejectInfo:TextArea;
		public var myGrid:DataGrid;
		public var rbUnaudit:RadioButton;
		public var rbPass:RadioButton;
		public var rbReject:RadioButton;
		public var item_box:HBox;
		public var subsText:TextArea;
		public var commonWords:ComboBox;
		
		//public var localCon:LocalConnection;
	    
		//private var type:String;	//产品类型
		private var bInSearch:Boolean;		//是否在搜索
		private var searchObj:Object;	//搜索关键字信息
		private var status:String;	//列表范围：未审核，通过，驳回，全部
		private var selectedIndex:int;    
		protected var delegate:ApplyClassDelegate;	
		private var latestMode:String = '0';		//上个作品的卡种
		
		private var currentType:String = TYPE_CARD;
		
		public var firstTimeLoad:Boolean = true;
		public const TYPE_BOOK:String = '1';
		public const TYPE_CARD:String = '2';  
		public const STATUS_UNAUDIT:String = '0';
		public const STATUS_PASS:String = '1';
		public const STATUS_REJECT:String = '2';  
		
		public var m_items:ArrayCollection;
		
        public var searchModes:ArrayCollection = new ArrayCollection(
            [ {label:"作品ID", data:0},
              {label:"宝宝号", data:1}, 
            ]);		
		
		public function ApplyClassAuditClass()
		{
			super();
			delegate = new ApplyClassDelegate(this);
			
			this.page = 0;
			this.bInSearch = false;
			this.selectedIndex = -1;
//			localCon = new LocalConnection();
//			localCon.addEventListener(StatusEvent.STATUS, onStatus);
			
			getPage();
		}
//		
//        private function onStatus(event:StatusEvent):void 
//        {
//            switch (event.level) 
//            {
//                case "status":
//                    trace("LocalConnection.send() succeeded");
//                    break;
//                case "error":
//                    trace("LocalConnection.send() failed");
//                    break;
//            }
//        }		
		
		public function onTypeClick(type:String):void
		{
			this.bInSearch = false;
			
			if( type == TYPE_CARD )
			{
				currentType = TYPE_CARD;
			}
			else if( type == TYPE_BOOK )
			{
				currentType = TYPE_BOOK;
			}
			
			getPage(0, currentType, currentStatus);
		}
		
		public function getStateTip(type:String):String
		{
			if(this.myGrid.selectedItem.status == STATUS_PASS)
			{
				return '已通过申精';
			}
			else if(this.myGrid.selectedItem.status == STATUS_REJECT)
			{
				return '已拒绝申精';
			}
			else
			{
				return '等待申精审核';
			}
		}
		
		public function onRangeClick(status:String):void
		{
			this.bInSearch = false;
			getPage(0, currentType, status);
		}	
		
		private function get currentStatus():String
		{
			var stus:String = '0';
			if(rbPass.selected)
			{
				stus = STATUS_PASS;
			}
			else if(rbReject.selected)
			{
				stus = STATUS_REJECT;
			}
			
			return stus;			
		}
		
		public function onRefreshClick():void
		{
			this.bInSearch = false;
			getPage(0, currentType, currentStatus);
		}
		
		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			
			getPage(page, currentType, currentStatus);
		}
		
		public function getPage(page:int=0, type:String=TYPE_CARD, status:String=STATUS_UNAUDIT):void
		{
			if (this.bInSearch)
			{
				this.delegate.getDataBySearch(this.searchObj, page);				
			}
			else
			{
				this.delegate.getDataByPage(page, type, status);
			}
		}

		public function onGetGameInfo( gameName:String, gameId:String ):void{
			if(gameName != ""){
				onGetGameId( gameName );
			}
			else if(gameId != ""){
				onGetGameName( gameId );
			}
		}
		
		public function onGetGameName( gameId:String ):void{
			var gameDelegate:GameDelegate = new GameDelegate( this );
			gameDelegate.getNameByGameId( gameId );
		}
		
		public function getNameByGameIdResult(result:Object, token:Object = null):void
		{
			var ret:Object = result.result;
			if( ret.code == 0 )
			{
				if( !ret.name )
				{
					Alert.show('没有找到这个游戏名称');
					return ;
				}
				item_game.text = ret.name;
			}
		}

		public function onGetGameId( gameName:String ):void
		{
			var gameDelegate:GameDelegate = new GameDelegate( this );
			gameDelegate.getIdByGameName( gameName );
		}
		
		public function getIdByGameNameResult(result:Object, token:Object = null):void
		{
			var ret:Object = result.result;
			if( ret.code == 0 )
			{
				if( !ret.gid )
				{
					Alert.show('没有找到这个游戏ID');
					return ;
				}
				item_gameid.text = ret.gid;
			}
		}				
		
		public function getDataResult(result:Object, token:Object = null):void
		{
			if(result.result.code == '0')
			{
				this.pageVolume = int(result.result.pageVolume);
				prepareData(result.result);
			}
		}
		
		private function prepareData(result:Object, method:String='get'):void
		{
			//预处理结果集
			if (method == "get")
			{
				this.m_items = new ArrayCollection(result.data);
				
				//显示分页
				this.page = result.page>0?result.page:0;
				this.pagecnt = result.pagecnt>1?result.pagecnt:1;
				this.makePageIndices();		
			}
			
			for each ( var item:Object in this.m_items )
			{
				if(item.catalogbak)
					item.catalogLabel = item.catalogbak.name + '('+item.catalogbak.id+')';		
				else
					item.catalogLabel = '';			
				
				item.oldid = item.id
				
				if (item._class > 0)
					item.classCheck = true;
				else
					item.classCheck = false;
									
				if (item.share > 0)
					item.shareCheck = true;
				else
					item.shareCheck = false;
				
				if (item.audit == 1)
					item.auditCheck = true;
				else
					item.auditCheck = false;

				if (item.audit == '-1')
					item.deleteCheck = true;
				else
					item.deleteCheck = false;
						
			}			
						
		}
		
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		public function gotoPage(page:String):void
		{
			if (page.length>0)
			{
				getPage(int(page)-1, currentType);
			}
		}	
		
		public function onSearch(type:int,pattern:String):void
		{
			pattern = StringUtil.trim(pattern);
			
			this.searchObj = new Object;
			
			this.searchObj.type = currentType;
			if (type == 0)
			{
				this.searchObj.assetid = pattern;
			}
			else if( type == 1)
			{
				this.searchObj.bid = pattern;
			}
			
			this.bInSearch = true;
			
			this.getPage(0); 
			
		}	
		
		public function onDataGridItemClick(isForce:Boolean=false, reflesh:Boolean=false):void
		{
			if (myGrid.selectedItem == null )	
				return;
			
			if ( myGrid.selectedIndex == this.selectedIndex && !reflesh )
				return;	
			
			item_rejectInfo.text = '';
			commonWords.selectedIndex = 0;
				
			this.selectedIndex = myGrid.selectedIndex;			
			item_box.enabled = true;
			
			var isDiffMode:Boolean = isForce;
			//连环画   new新的
			if( currentType == TYPE_BOOK )
			{
				if( item_player && item_player.source && String(item_player.source).indexOf('bookplayerforbackadmin.swf') < 0 )
				{
					isDiffMode = true;
				}
				latestMode = '-1';
			}
			else if(this.myGrid.selectedItem.mode)
			{
				if(this.myGrid.selectedItem.mode != latestMode) 
				{
					isDiffMode = true;
					latestMode = this.myGrid.selectedItem.mode;	
				}
			}			
			
			if (item_player)
			{
				try
				{
					Object(item_player.content).application.player.stopPlay();
				}
				catch( e:Error )
				{
					trace( e.getStackTrace() );
				}
			}
			else
			{
				isDiffMode = true;
			}				
			
			Application.application.parameters.info = myGrid.selectedItem.flashVars;
			
			if(isDiffMode)
			{
				if( item_player.numChildren > 0 )
				{
					GCUtil.runGc();
				}
				
				var player:SWFLoader = getPlayerInPools( latestMode );
				
				item_playerBox.removeAllChildren();		
						
				if( player && !isForce )
				{
					item_player = player;
					Object(item_player.content).application.model.refleshParameters();
				}
				else
				{
					delPlayerFormPools( latestMode );
					
					item_player = null;
					item_player = new SWFLoader();
					item_player.width = 635;
					item_player.height = 500;	
					item_player.id = "item_player";
					item_player.autoLoad = false;
					item_player.scaleContent = true;
					item_player.source = this.myGrid.selectedItem.player;
					
					item_player.load();
					item_player.addEventListener(Event.INIT,playerInit);
					
					addPlayerPool( item_player, latestMode );
				}
				
				item_playerBox.addChild(item_player);
				
				firstTimeLoad = false;
			}	
			else
			{
				if(firstTimeLoad)
				{
					if(latestMode == '-1')
					{
						item_player.source = "http://www1.aipai.com/app/www/player/bookplayerforbackadmin.swf";
					}
					else
					{
						item_player.source = "http://www1.aipai.com/app/www/player/babycardplayer.swf";
					}
					item_player.autoLoad = true;
					firstTimeLoad = false;
				}
				else
				{
					Object(item_player.content).application.model.refleshParameters();
				}
//				localCon.send("Player_swf","playNewSource");
			}					
					
		}
		
		private var playerPools:Array = new Array;
		private function addPlayerPool( player:SWFLoader, mode:String ):void
		{
			if( !playerPools )
			{
				playerPools = new Array();
			}
			playerPools.push( {mode:mode, player:player} );
		}
		
		private function getPlayerInPools( mode:String ):SWFLoader
		{
			if( playerPools )
			{	
				for each( var obj:Object in playerPools )
				{
					if( obj.mode == mode )
					{
						return (obj.player as SWFLoader);
					}
				}
			}
			
			return null; 	
		}
		
		private function delPlayerFormPools( mode:String ):void
		{
			if( playerPools )
			{
				for( var i:int=0; i<playerPools.length; i++ )
				{
					if( playerPools[i].mode == mode )
					{
						var player:SWFLoader = (playerPools[i].player as SWFLoader);
						player.source = '';
						player.load( null );
						playerPools.splice( i, 1 );
						//player.parent.removeChild( player );
						
						return ;
					}
				}
			}
		}  		

		public function playerInit(evt:Event):void
		{
			evt.target.content.addEventListener(FlexEvent.APPLICATION_COMPLETE, appOk, true);
		}
		
		public function appOk(evt:Event):void
		{
			evt.target.addEventListener("subsLoaded",subsLoadedEvt);
		}
		
		public function subsLoadedEvt(evt:Event):void
		{
			var data:*;
			var effectData:*;
			
			if( this.currentType == TYPE_BOOK )
			{
				data = evt.target.model.pagesInfo;
			}
			else
			{
				data = evt.target.model.subs;
				effectData = evt.target.model.effectTexts;				
			}
			
			showSubs(data);
			showEffectTexts(effectData);
		}
		
		public function showSubs(xmlListCol:*):void
		{
			var text:String = "<b>字幕</b>：(出现时间)\n";
			
			if(currentType == TYPE_BOOK)
			{
				for ( var i:int = 0; i < xmlListCol.page.length(); ++i )        
	            {
	            	text += "<b>"+xmlListCol.page[i].@realText+"</b>  (第"+ int(i+1) + "图)\n";
	            }				
			}
			else
			{
				for each ( var sub:XML in xmlListCol )
				{
					var str:String = unescape(sub.@text);
					var myPattern:RegExp = /\scolor=\S*\s/gi;  
					str = str.replace(myPattern, " color='#333333' ");  
					var sizePattern:RegExp = /\ssize=\S*\s/gi; 
					str = str.replace(sizePattern, " size='14' ");
					
					text += str +"  ("+ int(sub.@time) + "--" + (int(sub.@time)+int(sub.@stay))  +")\n";	
				}
			}
			
			subsText.htmlText = text;
		}

		public function showEffectTexts(xmlListCol:*):void
		{
			var text:String = "\n\n <b>特效字幕</b>：\n";
			
			for each ( var effectText:XML in xmlListCol )
			{
				text += "<b>"+effectText.@text+"</b> \n";	
			}
			
			subsText.htmlText += text;
		}										
		
	 	public function onLabelPlayPageClick():void
	 	{
	 		var u:URLRequest = new URLRequest(myGrid.selectedItem.url); 
	 		navigateToURL(u,"_blank"); 
	 	}
	 	
        public function onLabelCopyUrlClick():void
        {
        	System.setClipboard(myGrid.selectedItem.url);
        }
        
		public function onLabelGoToZoneClick():void
		{
	 		var u:URLRequest = new URLRequest("http://www.aipai.com/space.php?bid=" + myGrid.selectedItem.bid);
	 		navigateToURL(u,"_blank");
		}
		
		private function updatePrepare():Object
		{
			if (myGrid.selectedItem == null)	
			{
				return null;
			}
			
			var update:Object = new Object;
			update.id = item_id.text;
			
			if(item_audit.selected)
			{
				update.status = STATUS_PASS;
			}
			else if(item_delete.selected)
			{
				update.status = STATUS_REJECT;
			}
			else
			{
				update.status = STATUS_UNAUDIT;
			}
			
			update.type = currentType;
			
			update.rejectInfo = item_rejectInfo.text;
			
			return update;
			
		}
		
		public function onSubmit(event:Event):void
		{
			//处理update					
			var update:Object = this.updatePrepare();
            if (!update)
            {
            	Alert.show("请先选择要审核的申精作品");
            	return;
            }
            
            if(checkAudit())
            {
            	var bPass:int = 0;
            	if(myGrid.selectedItem.audit == '-1')
            	{
            		update.status = STATUS_REJECT;
            		update.rejectInfo = '作品已经被删除了！';
            		
            		Alert.show('该作品已经被客服删除了，申精已经被拒绝！');
            	}
            	else if(myGrid.selectedItem.audit == '1')
            	{
            		//已经审核通过并且不是精华作品
            		if(myGrid.selectedItem._class <= 0 && update.status == STATUS_PASS)
            		{
            			bPass = 1;
            		}
            	}
            	
            	this.delegate.setStatus(update.id, update.type, update.status, update.rejectInfo, bPass, myGrid.selectedItem.title, item_title.text, item_adwords.text, item_catalog.text);
            	LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.APPLYCLASS_AUDIT, LogUtil.UPDATE, {assetid:update.id,updated:update}, update.id, currentType, true);
            }
            
		} 
		
		private function checkAudit():Boolean
		{
			if(myGrid.selectedItem.audit == '0')
			{
				Alert.show('该作品尚未审核，请等待客服审核作品后再审核申精作品!');
				return false;
			}
			else if(myGrid.selectedItem.audit == '100')
			{
				Alert.show('该作品需要重新审核，请等待客服审核作品后再审核申精作品!');
				return false;
			}
			
			return true;
			
		}
		
		public function setStatusResult(result:Object, token:Object = null):void
		{
			var ret:Object = result.result;
			if(ret.code != '0')
			{
				Alert.show(ret.msg);
			}
			else
			{
				for each (var item:Object in m_items)
				{
					if(item.id == ret.data.id)
					{
						item.status = ret.data.status;
						item.rejectInfo = ret.data.rejectInfo;
						return ;
					}
				}
			}
		}
		
		public function onPlayerError(event:Event):void
		{
			    	 			
		}
		
		public function onBtnBackClick():void
		{
			this.verticalScrollPosition = 0;
		}
		
		public function onBtnStopClick():void
		{
//			if (localCon)
//				localCon.send("Player_swf","playerStop");	
			try
			{
				Object(item_player.content).application.player.stopPlay();
			}
			catch( e:Error )
			{
				trace( e.getStackTrace() );
			}		
		}
		
		public function getNext(event:MouseEvent, isForce:Boolean=false):void
		{
			if(myGrid.selectedIndex == m_items.length - 1)
			{
				onBtnBackClick();
				return ;
			}			
			
			myGrid.selectedIndex++;
			onDataGridItemClick(isForce);
		}
		
		public function getPrev(event:MouseEvent, isForce:Boolean=false):void
		{
			if(myGrid.selectedIndex == 0)
			{
				onBtnBackClick();
				return ;
			}
			
			myGrid.selectedIndex--;
			onDataGridItemClick(isForce);			
		}
		
		public function refleshCurrentWork(event:Event):void
		{
			onDataGridItemClick(true, true);
		}
		
		public function onDelClick( event:MouseEvent ):void
		{
			Alert.show( '确认删除这条记录，让用户可以对该作品重新申请精华吗？', '提示', Alert.YES | Alert.NO, null, onConfirm );
		}
		
		private function onConfirm( evnet:CloseEvent ):void
		{
			if( evnet.detail == Alert.YES )
			{
				this.delegate.delData( item_id.text, currentType, item_rejectInfo.text );
			}	
		}
		
		public function delDataResult( result:Object, token:Object = null ):void
		{
			var ret:Object = result.result;
			if(ret.code != '0')
			{
				Alert.show(ret.msg);
			}
			else
			{
				for(var i:int=0; i<m_items.length; i++)
				{
					if(m_items.getItemAt(i).id == ret.id)
					{
						m_items.removeItemAt(i);
						Alert.show( '删除记录成功，该作品可以重新申请精华了。');
						return ;
					}
				}
			}			
		}
		
		private function makePageIndices():void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		} 												
		
	}
}